﻿package
{	
	import com.junkbyte.console.Cc;
	import com.junkbyte.console.Console;
	import com.junkbyte.console.ConsoleChannel;		
	
	import social.VKontakte.VKProvider;
	import social.VKontakte.VKUserRequest;
	import social.VKontakte.VKUserFields;
	import social.VKontakte.VKUserInfo;	
	import social.VKontakte.VKEvents;
	import social.VKontakte.VKProfileEvent;
	
	import flash.display.MovieClip;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.display.Loader;
	import flash.system.Security;
	import flash.system.LoaderContext;
	import flash.system.ApplicationDomain;

	public class GameLoader extends MovieClip 
	{
		private const CHost:String = 'http://62.212.69.47/';
		private const CSettingsURL:String = CHost + 'game.xml';
		
		private var FSettings:GameSettings;
		
		private var FSocialProvider:VKProvider;
		private var FUserInfo:VKUserRequest;
		private var FProfile:VKUserInfo;
		private var FPrelaoder:GamePreloader;
		
		private var FLoader:Loader;
		
		public function GameLoader() 
		{			
			addEventListener(Event.ADDED_TO_STAGE, OnInit);			
		}
		
		private function UpdateSecurity(APath:String):void
		{					
			var vHost:String = APath.substr(7, APath.length).split('.')[0];
			
			Cc.log('Loading security file from: ' + "http://" + vHost + ".vkontakte.ru/crossdomain.xml");
			
			Security.loadPolicyFile("http://" + vHost + ".vkontakte.ru/crossdomain.xml");
			Security.loadPolicyFile("http://" + vHost + ".vk.com/crossdomain.xml");
		}
		
		private function OnInit(e:Event):void
		{
			FPrelaoder = getChildByName('ClientPreloader') as GamePreloader;
			
			Security.loadPolicyFile('http://vkontakte.ru/crossdomain.xml');
			Security.loadPolicyFile('http://vk.com/crossdomain.xml');
			Security.loadPolicyFile(CHost + 'crossdomain.xml');
			
			SetupConsole();
			//Stage 1 - Loading game settings
			FSettings = new GameSettings(CSettingsURL);
			FSettings.addEventListener(FSettings.DATA_LOADED, OnSettingsLaoded);
			FSettings.Load();
		}
		
		private function OnSettingsLaoded(e:Event):void
		{
			UpdateSecurity(FSettings.ClientURL);
			//Stage 2 - connecting to VK
			FSocialProvider = new VKProvider(stage);
			FSocialProvider.addEventListener(VKEvents.VK_PROFILE_LOADED, OnCurrentUserProfile);
			FSocialProvider.Connect();
			//Requesting basic user info
			FUserInfo = new VKUserRequest(FSocialProvider.UserID);
			FUserInfo.Add(VKUserFields.PhotoMedium);
			FSocialProvider.RequestUserInfo(FUserInfo);	
			
			FSettings.removeEventListener(FSettings.DATA_LOADED, OnSettingsLaoded);
		}
		
		private function OnCurrentUserProfile(e:VKProfileEvent):void
		{			
			//Stage 3 - loading client
			FProfile = e.VKProfile;
			FLoader = new Loader();
			FLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, OnProgress);
			FLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, OnLoaded);			
			FLoader.load(new URLRequest(FSettings.ClientURL), new LoaderContext(true));
			
			FSocialProvider.removeEventListener(VKEvents.VK_PROFILE_LOADED, OnCurrentUserProfile);
			
			Cc.log('User name: ' + e.VKProfile.FirstName + ' ' + e.VKProfile.LastName);
		}
		
		private function OnProgress(e:ProgressEvent):void
		{
			Cc.log('Client: ' + Math.floor(e.bytesLoaded / e.bytesTotal * 100));
			FPrelaoder.Percent = e.bytesLoaded / e.bytesTotal;
		}
		
		private function OnLoaded(e:Event):void
		{
			var vGame:MovieClip;
			removeChild(FPrelaoder);
			if(FSocialProvider.TestMode)
			{
				Cc.log('Working in test mode');
				
				FLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, OnLoaded);
				FLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, FakeLoad);
				FLoader.loadBytes(FLoader.contentLoaderInfo.bytes, new LoaderContext(false, ApplicationDomain.currentDomain));
				
				function FakeLoad(vEvent:Event):void
				{
					vGame = MovieClip(vEvent.target.content);
					SetupOnStage(vGame);
				}
			}
			else
			{
				vGame = MovieClip(e.target.content);			
				SetupOnStage(vGame);
			}		
		}
		
		private function SetupOnStage(ATarget:MovieClip):void
		{			
			addChild(ATarget);
		}	
		
		private function SetupConsole():void
		{			
			Cc.config.style.backgroundAlpha = 0.8;
			Cc.config.style.topMenu = false;		
			Cc.startOnStage(this, "`");
			Cc.width = stage.stageWidth;
			Cc.height = 300;
			Cc.fpsMonitor = true;
			Cc.commandLine = true;
			Cc.config.commandLineAllowed = true;
		}
		
		public function get Provider():VKProvider
		{
			return FSocialProvider;
		}
		
		public function get Settings():GameSettings
		{
			return FSettings;
		}
		
		public function get Profile():VKUserInfo
		{
			return FProfile;
		}
	}	
}
